package com.secxiot.consumer.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.secxiot.common.constant.FileEnum;
import com.secxiot.common.constant.ServerStatusEnum;
import com.secxiot.common.entity.ResultVo;
import com.secxiot.common.exception.BaseException;
import com.secxiot.common.utils.Base64Utils;
import com.secxiot.common.utils.CachedBeanCopier;
import com.secxiot.common.utils.IdWorker;
import com.secxiot.common.utils.IdcardPicUtil;
import com.secxiot.config.FileConfig;
import com.secxiot.consumer.system.service.SystemConsumerService;
import com.secxiot.consumer.user.feign.UserClient;
import com.secxiot.provider.system.dto.*;
import com.secxiot.provider.system.entity.AppRecommend;
import com.secxiot.provider.system.entity.FileLog;
import com.secxiot.provider.system.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "系统模块")
@RequestMapping("system")
@RestController
public class SystemConsumerController {
    @Autowired
    private UserClient userClient;

    @Autowired
    private FileConfig fileConfig;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SystemConsumerService systemConsumerService;

    private static Logger log = LoggerFactory.getLogger(SystemConsumerController.class);

    @ApiOperation(value = "数据字典")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentCode", value = "父节点", required = false, dataType = "String")
    })
    @GetMapping("/dataDict")
    public ResultVo<List<DataDictVo>> listDataDict(@RequestParam(required = false) String parentCode) {
        List<DataDictVo> list = userClient.listDataDict(parentCode);
        return new ResultVo<List<DataDictVo>>(list);
    }

    @ApiOperation(value = "显示注册角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentCode", value = "父节点", required = false, dataType = "String")
    })
    @GetMapping("/dataDictUser")
    public ResultVo<List<DataDictVo>> listData(@RequestParam(required = false) String parentCode) {
        List<DataDictVo> list = userClient.listDataDict(parentCode);

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCode().equals("0000100003") || list.get(i).getCode().equals("0000100005") || list.get(i).getCode().equals("0000100006") || list.get(i).getCode().equals("0000100007")) {
                list.remove(i--);
            }
        }
        return new ResultVo<List<DataDictVo>>(list);
    }

    @ApiOperation(value = "普通任务任务类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentCode", value = "父节点", required = false, dataType = "String")
    })
    @GetMapping("/dataDictType")
    public ResultVo<List<DataDictVo>> listDataTask(@RequestParam(required = false) String parentCode) {
        List<DataDictVo> list = userClient.listDataDict(parentCode);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCode().equals("0000200001") || list.get(i).getCode().equals("0000200005") || list.get(i).getCode().equals("0000200003")) {
                list.remove(i--);
            }
        }
        return new ResultVo<List<DataDictVo>>(list);
    }

    @ApiOperation(value = "错误码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "errorCode", value = "错误码", required = false, dataType = "Integer")
    })
    @GetMapping("/errorCode")
    public ResultVo<List<Map<String, Object>>> listErrorCode(@RequestParam(required = false) Integer errorCode) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ServerStatusEnum exceptionEnum : ServerStatusEnum.values()) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", exceptionEnum.getStatus());
            map.put("message", exceptionEnum.getMessage());
            if (errorCode == null || exceptionEnum.getStatus() == errorCode) {
                list.add(map);
            }
        }
        return new ResultVo<>(list);
    }

    @ApiOperation(value = "根据code获取文件信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "文件编码", required = true, dataType = "String")
    })
    @GetMapping("/filelog/fileLogByCode")
    public ResultVo<List<FileLogVo>> selectFileByCode(@RequestParam(value = "code", required = false) String code) {
        return new ResultVo<>(userClient.selectFileByCode(code));
    }

    @ApiOperation(value = "Base64上传文件", httpMethod = "POST")
    @PostMapping("/upload")
    public ResultVo<List<FileLogVo>> listErrorCode(@RequestBody(required = true) List<FileReDto> files) {
        List<FileLogVo> logIdS = new ArrayList<>();
        for (FileReDto file : files) {
            LocalDate now = LocalDate.now();
            StringBuilder uri = new StringBuilder(File.separator).append(now.getYear())
                    .append(File.separator).append(now.getMonth().getValue())
                    .append(File.separator).append(now.getDayOfMonth())
                    .append(File.separator).append(idWorker.nextId()).append(".").append(file.getExtention());
            String filePath = fileConfig.getUpload() + uri.toString();
            File f = new File(filePath);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            boolean b = Base64Utils.Base64ToImage(file.getFile(), f.getPath());
            log.info("Upload success,filepath:" + filePath);
            //保存日志
            FileLog fileLog = new FileLog();
            fileLog.setId(idWorker.nextId());
            fileLog.setFileType(file.getFileType());
            fileLog.setFileUri(uri.toString());
            fileLog.setCreateDate(new Date());
            fileLog.setUsedFlag(0);
            userClient.saveFileLog(fileLog);
            logIdS.add(FileLogVo.builder().fileType(file.getFileType()).fileLogId(fileLog.getId()).fileUri(uri.toString()).build());
        }
        return new ResultVo<List<FileLogVo>>(logIdS);
    }

    @ApiOperation(value = "选择文件流上传文件", httpMethod = "POST")
    @PostMapping("/uploadFile")
    public ResultVo<FileLogVo> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("fileType") String fileType, @RequestParam("extention") String extention) {
        LocalDate now = LocalDate.now();
        StringBuilder uri = new StringBuilder(File.separator).append(now.getYear())
                .append(File.separator).append(now.getMonth().getValue())
                .append(File.separator).append(now.getDayOfMonth())
                .append(File.separator).append(idWorker.nextId()).append(".").append(extention);
        String filePath = fileConfig.getUpload() + uri.toString();
        File f = new File(filePath);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        try {
            file.transferTo(f);
        } catch (IllegalStateException | IOException e) {
            return new ResultVo<>(new BaseException(ServerStatusEnum.UPLOAD_FILE_FAILURE));
        }
        log.info("Upload success,filepath:" + filePath);
        //保存日志
        FileLog fileLog = new FileLog();
        fileLog.setId(idWorker.nextId());
        fileLog.setFileType(fileType);
        fileLog.setFileUri(uri.toString());
        fileLog.setCreateDate(new Date());
        fileLog.setUsedFlag(0);
        Long id = userClient.saveFileLog(fileLog);
        FileLogVo vo = FileLogVo.builder().fileType(fileType).fileLogId(fileLog.getId()).fileUri(uri.toString()).build();
        return new ResultVo<>(vo);
    }

    @ApiOperation(value = "选择文件流上传文件Code", httpMethod = "POST")
    @PostMapping("/uploadFileCode")
    public ResultVo<FileLogVo> uploadFileCode(@RequestParam("file") MultipartFile file, @RequestParam("extention") String extention, @RequestParam("code") String code) {

        LocalDate now = LocalDate.now();
        String fileName = file.getOriginalFilename();
        String fileExtention = fileName.substring(fileName.lastIndexOf("."));

        StringBuilder uri = new StringBuilder(File.separator).append(now.getYear())
                .append(File.separator).append(now.getMonth().getValue())
                .append(File.separator).append(now.getDayOfMonth())
                .append(File.separator).append(idWorker.nextId()).append(fileExtention);
        String filePath = fileConfig.getUpload() + uri.toString();
        File f = new File(filePath);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        try {
            file.transferTo(f);
        } catch (IllegalStateException | IOException e) {
            return new ResultVo<>(new BaseException(ServerStatusEnum.UPLOAD_FILE_FAILURE));
        }
        log.info("Upload success,filepath:" + filePath);
        //保存日志
        FileLog fileLog = new FileLog();
        String fileType = FileEnum.getByCode(fileExtention).code;
        fileLog.setId(idWorker.nextId());
        fileLog.setFileType(fileType);
        fileLog.setFileUri(uri.toString());
        fileLog.setCreateDate(new Date());
        fileLog.setUsedFlag(0);
        fileLog.setCode(code);
        userClient.saveFileLog(fileLog);
        FileLogVo vo = FileLogVo.builder().fileType(fileType).fileLogId(fileLog.getId()).fileUri(uri.toString()).code(code).build();
        return new ResultVo<>(vo);
    }

    @ApiOperation(value = "选择文件流上传文件(多文件)", httpMethod = "POST")
    @PostMapping("/uploadFiles")
    public ResultVo<List<FileLogVo>> uploadFiles(@RequestParam("files") MultipartFile[] files) {
        List<FileLogVo> logVoList = new ArrayList<FileLogVo>();
        String code = System.currentTimeMillis() + "";
        //循环获取file数组中得文件
        Date date = new Date();
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                log.info("Upload error,filepath:" + file);
                continue;
            }
            String fileName = file.getOriginalFilename();
            String fileExtention = fileName.substring(fileName.lastIndexOf("."));
            LocalDate now = LocalDate.now();
            StringBuilder uri = new StringBuilder(File.separator).append(now.getYear())
                    .append(File.separator).append(now.getMonth().getValue())
                    .append(File.separator).append(now.getDayOfMonth())
                    .append(File.separator).append(idWorker.nextId()).append(fileExtention);
            String filePath = fileConfig.getUpload() + uri.toString();
            File f = new File(filePath);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            try {
                file.transferTo(f);
            } catch (IllegalStateException | IOException e) {
                return new ResultVo<>(new BaseException(ServerStatusEnum.UPLOAD_FILE_FAILURE));
            }

            String fileType = FileEnum.getByCode(fileExtention).code;
            //保存日志
            FileLog fileLog = new FileLog();
            fileLog.setId(idWorker.nextId());
            fileLog.setFileType(fileType);
            fileLog.setFileUri(uri.toString());
            fileLog.setCreateDate(date);
            fileLog.setUsedFlag(0);
            fileLog.setCode(code);
            userClient.saveFileLog(fileLog);
            FileLogVo vo = FileLogVo.builder().fileType(fileType).fileLogId(fileLog.getId()).fileUri(uri.toString()).code(code).build();
            logVoList.add(vo);
        }
        return new ResultVo<List<FileLogVo>>(logVoList);
    }

    @ApiOperation(value = "发布任务获取用户类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "taskType", value = "任务类型", required = true, paramType = "form")
    })
    @GetMapping("/list")
    public ResultVo<List<UserTypeVo>> getUserTypeList(
            @RequestParam(value = "userId", required = true) Long userId,
            @RequestParam(value = "taskType", required = true) String taskType
    ) {
        return new ResultVo<>(systemConsumerService.getUserTypeList(userId, taskType));
    }

    @ApiOperation(value = "获取最新版本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "platform", value = "平台类型，字典00011", required = true, paramType = "query"),
            @ApiImplicitParam(name = "clientType", value = "客户端类型，患者端：patient 医生端：doctor", required = true, paramType = "query")
    })
    @GetMapping("/app/version")
    public ResultVo<AppVersionVo> getAppVersion(@RequestParam String platform, @RequestParam String clientType) {
        AppVersionDto appVersion = userClient.getAppVersion(platform, clientType);
        AppVersionVo vo = new AppVersionVo();
        CachedBeanCopier.copy(appVersion, vo);
        return new ResultVo<>(vo);
    }

    @ApiOperation(value = "获取banner图,资讯列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "hospitalId", value = "医院id", required = false, paramType = "query", dataType = "Long")
    })
    @GetMapping("/app/home")
    public ResultVo<AppBannerAndNewsVo> getAppBanner(@RequestParam(value = "userId", required = true) Long userId,
                                                     @RequestParam(value = "hospitalId", required = false) Long hospitalId
    ) {
        List<AppBannerDto> bs = userClient.getAppBanner(userId, hospitalId);
        List<AppBannerVo> collect = bs.stream().map(b -> {
            AppBannerVo d = new AppBannerVo();
            CachedBeanCopier.copy(b, d);
            return d;
        }).collect(Collectors.toList());
        AppBannerAndNewsVo app = new AppBannerAndNewsVo();
        app.setAppBanners(collect);

        List<AppNewsDto> ns = userClient.getAppNews(userId, hospitalId);
        List<AppNewsVo> news = ns.stream().map(b -> {
            AppNewsVo d = new AppNewsVo();
            CachedBeanCopier.copy(b, d);
            return d;
        }).collect(Collectors.toList());
        app.setAppNews(news);
        return new ResultVo<>(app);
    }

    @ApiOperation(value = "获取推荐列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "hospitalId", value = "医院id", required = false, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "pageSize", value = "条数", required = true, paramType = "query", dataType = "Long")
    })
    @GetMapping("/app/recommendList")
    public ResultVo<List<AppRecommendVo>> getAppRecommends(@RequestParam(value = "userId", required = true) Long userId,
                                                           @RequestParam(value = "hospitalId", required = false) Long hospitalId,
                                                           @RequestParam(value = "pageNo", required = true) Long pageNo,
                                                           @RequestParam(value = "pageSize", required = true) Long pageSize
    ) {
        List<AppRecommend> rs = userClient.getAppRecommends(userId, hospitalId, pageNo, pageSize);
        List<AppRecommendVo> appRecommendVos = rs.stream().map(b -> {
            AppRecommendVo d = new AppRecommendVo();
            CachedBeanCopier.copy(b, d);
            return d;
        }).collect(Collectors.toList());
        return new ResultVo<List<AppRecommendVo>>(appRecommendVos);
    }

    /*@ApiOperation(value = "获取推荐详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "recommendId", value = "推荐内容id", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "hospitalId", value = "医院id", required = false, paramType = "query", dataType = "Long")
    })
    @GetMapping("/app/recommend/detail")
    public ResultVo<AppRecommendVo> getAppRecommend(@RequestParam(value = "userId",required = true) Long userId,
                                                          @RequestParam(value = "recommendId",required = true) Long recommendId,
                                                          @RequestParam(value = "hospitalId",required = false)  Long hospitalId
    ) {
        AppRecommend appRecommend = userClient.getAppRecommendById(recommendId);
        AppRecommendVo appRecommendVo = new AppRecommendVo();
        if(null != appRecommend){
            CachedBeanCopier.copy(appRecommendVo, appRecommend);
        }
        return new ResultVo<>(appRecommendVo);
    }*/

    /****************************************资料库**************************************************/

    @ApiOperation(value = "资料库--列表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "hospitalId", value = "医疗机构Id", required = false, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "条数", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "isPage", value = "是否分页  0 否  1 是", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "searchName", value = "搜索关键字", required = false, paramType = "query", dataType = "String")
    })
    @GetMapping("/filesStorage/list")
    public ResultVo<List<FilesStorageVo>> selectNarcoticUserInfoPage(
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "hospitalId", required = false) Long hospitalId,
            @RequestParam(value = "pageNo", required = false) Integer pageNo,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "isPage", required = true) Integer isPage,
            @RequestParam(value = "searchName", required = false) String searchName) {
        if (isPage == 1) {
            if (pageNo == null) {
                return new ResultVo<List<FilesStorageVo>>(ServerStatusEnum.PAGENO_EMPTY);
            }
            if (pageSize == null) {
                return new ResultVo<List<FilesStorageVo>>(ServerStatusEnum.PAGESIZE_EMPTY);
            }
        }
        return new ResultVo<List<FilesStorageVo>>(userClient.selectFilesStorage(userId, hospitalId, pageNo, pageSize, isPage, searchName));
    }

    @ApiOperation(value = "资料库--详情", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资料库id", required = true, paramType = "query", dataType = "Long")
    })
    @GetMapping("/filesStorage/detail")
    public ResultVo<FilesStorageVo> getNarcoticUserInfoById(
            @RequestParam(value = "id", required = true) Long id) {
        return new ResultVo<FilesStorageVo>(userClient.getFilesStorageById(id));
    }

    @ApiOperation(value = "资料库--添加", httpMethod = "POST")
    @PostMapping("/filesStorage/insert")
    public ResultVo<Long> insertNarcoticUserInfo(@RequestBody FilesStorageDto filesStorageDto) {
        FilesStorageVo filesStorageVo = new FilesStorageVo();
        CachedBeanCopier.copy(filesStorageDto, filesStorageVo);
        return new ResultVo<Long>(userClient.insertFilesStorage(filesStorageVo));
    }

    @ApiOperation(value = "资料库--修改", httpMethod = "POST")
    @PostMapping("/filesStorage/update")
    public ResultVo<Long> updateNarcoticUserInfoById(@RequestBody FilesStorageDto filesStorageDto) {
        FilesStorageVo filesStorageVo = new FilesStorageVo();
        CachedBeanCopier.copy(filesStorageDto, filesStorageVo);
        return new ResultVo<Long>(userClient.updateFilesStorage(filesStorageVo));
    }

    /********************************医院文化制度***************************************/

    /**
     * 医院文化制度--列表
     *
     * @param type       数据字典 00015
     * @param hospitalId 医疗机构ID
     * @param pageNo     页数
     * @param pageSize   条数
     * @param isPage     是否分页  0 否  1 是
     * @param searchName 关键字
     * @return
     */
    @ApiOperation(value = "医院文化制度--列表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "数据字典 00015", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "hospitalId", value = "医疗机构Id", required = false, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "条数", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "isPage", value = "是否分页  0 否  1 是", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "searchName", value = "搜索关键字", required = false, paramType = "query", dataType = "String")
    })
    @GetMapping("/appRegime/list")
    public ResultVo<List<AppRegimeVo>> getAppRegimeByType(
            @RequestParam(value = "type", required = true) String type,
            @RequestParam(value = "hospitalId", required = false) Long hospitalId,
            @RequestParam(value = "pageNo", required = false) Integer pageNo,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "isPage", required = true) Integer isPage,
            @RequestParam(value = "searchName", required = false) String searchName) {
        if (isPage == 1) {
            if (pageNo == null) {
                return new ResultVo<List<AppRegimeVo>>(ServerStatusEnum.PAGENO_EMPTY);
            }
            if (pageSize == null) {
                return new ResultVo<List<AppRegimeVo>>(ServerStatusEnum.PAGESIZE_EMPTY);
            }
        }
        List<AppRegimeVo> appRegimeVs = userClient.selectAppRegime(type, hospitalId, pageNo, pageSize, isPage, searchName);
        return new ResultVo<List<AppRegimeVo>>(appRegimeVs);
    }

    /**
     * 医院文化制度--详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "医院文化制度--详情", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资料库id", required = true, paramType = "query", dataType = "Long")
    })
    @GetMapping("/appRegime/detail")
    public ResultVo<AppRegimeVo> getAppRegimeById(@RequestParam("id") Long id) {
        return new ResultVo<AppRegimeVo>(userClient.getAppRegimeById(id));
    }

    /**
     * 身份证号获取信息
     *
     * @param imgUrl 图片路径
     * @return
     */
    @ApiOperation(value = "身份证识别", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imgUrl", value = "图片路径", required = true, paramType = "query", dataType = "String")
    })
    @PostMapping("/discernIdcard")
    public ResultVo<JSONObject> discernIdcard(@RequestParam("imgUrl") String imgUrl) {
        String filePath = fileConfig.getUpload() + imgUrl;
        String fileBase64 = Base64Utils.ImageToBase64ByLocal(filePath);

        String result = IdcardPicUtil.idcardBase64(fileBase64, "id_card_side=front");
        log.info("身份证识别======result=>" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String imageStatus = jsonObject.getString("image_status");
        if ("normal".equals(imageStatus)) {//识别正常
            JSONObject wordsResultObject = jsonObject.getJSONObject("words_result");
            JSONObject addressObject = wordsResultObject.getJSONObject("住址");
            JSONObject nameObject = wordsResultObject.getJSONObject("姓名");
            JSONObject idCardNoObject = wordsResultObject.getJSONObject("公民身份号码");
            JSONObject sexObject = wordsResultObject.getJSONObject("性别");
            JSONObject nationObject = wordsResultObject.getJSONObject("民族");
            JSONObject data = new JSONObject();
            data.put("address", addressObject.getString("words"));
            data.put("name", nameObject.getString("words"));
            data.put("idCardNo", idCardNoObject.getString("words"));
            data.put("sex", sexObject.getString("words"));
            data.put("nation", nationObject.getString("words"));
            data.put("age", IdcardPicUtil.getPersonAgeFromIdCard(idCardNoObject.getString("words")));
            return new ResultVo<JSONObject>(data);
        }
        String message = "";
        if ("reversed_side".equals(imageStatus)) {
            message = "身份证正反面颠倒";
        } else if ("reversed_side".equals(imageStatus)) {
            message = "上传的图片中不包含身份证";
        } else if ("reversed_side".equals(imageStatus)) {
            message = "身份证模糊";
        } else if ("reversed_side".equals(imageStatus)) {
            message = "其他类型证照";
        } else if ("reversed_side".equals(imageStatus)) {
            message = "身份证关键字段反光或过曝";
        } else if ("reversed_side".equals(imageStatus)) {
            message = "身份证欠曝（亮度过低）";
        } else if ("unknown".equals(imageStatus)) {
            message = "身份证不能识别";
        } else {
            message = "身份证不能识别";
        }
        return new ResultVo<JSONObject>(message, false, 500, null);
    }

    @ApiOperation(value = "复制文件", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "oldPath", value = "图片路径", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping("/copyFile")
    public ResultVo<FileLogVo> copyPhotoAndRename(@RequestParam(value = "code", required = true) String code,
                                                  @RequestParam(value = "oldPath", required = true) String oldPath) {
        String filePath = fileConfig.getUpload();
        String fileExtention = oldPath.substring(oldPath.lastIndexOf("."));
        LocalDate now = LocalDate.now();
        StringBuilder uri = new StringBuilder(File.separator).append(now.getYear())
                .append(File.separator).append(now.getMonth().getValue())
                .append(File.separator).append(now.getDayOfMonth())
                .append(File.separator).append(idWorker.nextId()).append(fileExtention);
        String newFilePath = fileConfig.getUpload() + uri.toString();

        File f = new File(newFilePath);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        try {
            FileInputStream fin = new FileInputStream(filePath + oldPath);
            FileOutputStream fout = new FileOutputStream(newFilePath);
            byte[] buffer = new byte[1024];
            while (fin.read(buffer) != -1) {
                fout.write(buffer);
            }
            fin.close();
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileLog fileLog = new FileLog();
        String fileType = FileEnum.getByCode(fileExtention).code;
        fileLog.setId(idWorker.nextId());
        fileLog.setFileType(fileType);
        fileLog.setFileUri(uri.toString());
        fileLog.setCreateDate(new Date());
        fileLog.setUsedFlag(0);
        if (!StringUtils.isEmpty(code)) {
            fileLog.setCode(code);
        }
        userClient.saveFileLog(fileLog);
        FileLogVo vo = FileLogVo.builder().fileType(fileType).fileLogId(fileLog.getId()).fileUri(uri.toString()).code(code).build();
        return new ResultVo<>(vo);
    }

    /**
     * 删除文件
     *
     * @param fileName 文件路径
     * @return
     */
    @ApiOperation(value = "删除文件", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "fileLogId", value = "文件id", required = true, paramType = "query", dataType = "Long")
    })
    @GetMapping("/deleteFile")
    public boolean deleteFile(@RequestParam(value = "fileName", required = true) String fileName,
                              @RequestParam(value = "fileLogId", required = true) Long fileLogId) {
        userClient.deleteFile(fileLogId);
        File file = new File(fileConfig.getUpload() + fileName);
        if (file.exists() && file.isFile()) {
            return file.delete();
        } else {
            return false;
        }
    }

}
